package com.dongdongqiang.admin.shiro;

import com.dongdongqiang.admin.enums.CacheName;
import com.dongdongqiang.admin.service.SysPermissionService;
import com.dongdongqiang.admin.service.SysRoleService;
import com.dongdongqiang.admin.service.SysUserService;
import com.dongdongqiang.common.base.BaseTreeVO;
import com.dongdongqiang.common.cache.CacheComponent;
import com.dongdongqiang.domain.sys.SysPermission;
import com.dongdongqiang.domain.sys.SysRole;
import com.dongdongqiang.domain.sys.SysUser;
import org.apache.commons.collections.SetUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by ZZB on 2017/10/29.
 */
public class AuthRealm extends AuthorizingRealm {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysPermissionService sysPermissionService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        SysUser user=(SysUser) principal.fromRealm(this.getClass().getName()).iterator().next();//获取session中的用户
        Set<String> permissions=new HashSet<>();
        List<SysRole> roles = sysRoleService.queryByUserId(user.getId());
        if(roles.size()>0) {
            for(SysRole role : roles) {
                List<SysPermission> sysPermissions = sysPermissionService.queryByRoleId(role.getId());
                if(sysPermissions.size()>0) {
                    for( SysPermission sysPermission : sysPermissions) {
                        permissions.add(sysPermission.getPermissionName());
                    }
                }
            }
        }
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.addStringPermissions(permissions);//将权限放入shiro中.
        info.addRoles(roles.stream().map(SysRole::getRoleName).collect(Collectors.toList()));
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken utoken=(UsernamePasswordToken) token;//获取用户输入的token
        String username = utoken.getUsername();
        SysUser user = sysUserService.getByUserName(username);
        return new SimpleAuthenticationInfo(user, user.getPassword(),this.getClass().getName());//放入shiro.调用CredentialsMatcher检验密码
    }

}
